package com.candy.control;

import com.candy.service.UserInfoService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@WebServlet("/addUserInfowithupload")
//当前请求的jsp页面中包含二进制文件，上传的图片最大不能超过56M
@MultipartConfig(maxFileSize = 5 * 1024 * 1024)
public class UserInfoAddWithUploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("访问后台成功............");
//        设置字符集，处理中文乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

 //        ============================图片上传==============================
        //图片上传
        Part img = req.getPart("file");//获取图片信息
//进行日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        //准备文件夹
        String format = sdf.format(new Date());
//        创建文件夹（以本地路径+当前时间进行文件夹的创建）
        File folder = new File("E:\\CodeSpace\\img",format);
//        判断该文件夹是否存在，若不存在，则创建
        if(!folder.exists()){
            folder.mkdirs();//文件夹的路径
        }
        String oldName = img.getSubmittedFileName();//获取文件名
        //UUID 全球唯一 IP 电脑配置 时间
        String fileName= UUID.randomUUID().toString() +oldName.substring(oldName.lastIndexOf("."));//对文件命名
        File file = new File(folder, fileName);
        //上传
        img.write(file.getAbsolutePath());
//        将上传后的路径进行保存，
        String imSrc="http://localhost:8086/img"+format+fileName;
        System.out.println(imSrc);


        //        ============================图片上传==============================


//调用业务逻辑处理层进行业务处理
        UserInfoService userInfoService=new UserInfoService();
       String username= req.getParameter("username");
       String userpwd= req.getParameter("userpwd");
       String useraddress= req.getParameter("useraddress");
       String userTel=  req.getParameter("usertel");
       userInfoService.addUserInfoWithUpload(username,userpwd,useraddress,userTel,imSrc);
//           若用户名密码正确，则跳转到登录成功页面
       req.getRequestDispatcher("WEB-INF/userManger/userInfoQuery.jsp").forward(req,resp);





    }
}
